var path = require('path')
    , fs = require('fs')
    , Q = require('avril.queue')
    , singleLoadReg = /RC\s*\.\s*ComponentMgr\s*\.\s*load\s*\(\s*(?:\'|\")((?:\S+)\.js)?(?:\'|\")/g
    , batchLoadReg = /RC\s*\.\s*ComponentMgr\s*\.\s*batchLoad\s*\(\s*(\[(?:\n|.)+?\])/g;

//TODO: use /RC\s*\.\s*ComponentMgr\s*\.\s*load\s*\(\s*(?:\'|\")(.+)(?:\'|\")/
// check cmpName computed in RC.load
// gzip http://archive.online-convert.com/convert-to-gz

function scsDesktopRoot() {
    return path.resolve(process.cwd(), 'scs/src/desktop');
}

module.exports = function (source) {
    var callback = this.async()
        , q = Q()
        , currentFilePath = this.resourcePath
        , resourcePath = currentFilePath.replace(/\.js$/, '/en_US.js')
        , hasResources;

    if (/en_US\.js$/gi.test(currentFilePath)) {
        return callback(null, source);
    }

    q.func(function (next) {
        fs.exists(resourcePath, function (exists) {
            hasResources = exists;
            next();
        });
    });

    q.func(function () {
        var currentFileName = path.basename(currentFilePath).replace(/.js$/, '');

        source = comment('current file', currentFilePath.replace(scsDesktopRoot(), '')) + '\n'
            + (hasResources ? ('require("./' + currentFileName + '/en_US.js"); // load resource: ./' + currentFileName + '/en_US.js\n') : '')
            + source;

        source = source.replace(singleLoadReg, function (match, cmpName) {
            return appendRequire(cmpName) + match;
        });

        source = source.replace(batchLoadReg, function (match, cmpNames) {
            var cmpArr = eval('(' + cmpNames + ')');
            var dependencies = cmpArr.map(function (cmpName) {
                    return appendRequire(cmpName) + comment('require:', cmpName);
                }).join('\n') + '\n';
            return dependencies + match;
        });

        callback(null, source);
    });

    function appendRequire(cmpName) {
        if (/\.css$|\.html$/.test(cmpName)) {
            return '';
        }

        if (!/\.js$/.test(cmpName)) {
            return '';
        }

        cmpName = cmpName.replace(/^\//, '');

        var requireFullPath = path.resolve(scsDesktopRoot(), cmpName);

        var relativePath = path.relative(path.dirname(currentFilePath), requireFullPath).replace(/\\/g, '/');

        relativePath = './' + relativePath;

        return 'require("' + relativePath + '");';
    }

    function comment() {
        return '//' + Array.prototype.slice.call(arguments).join(' ');
    }
};